<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import {
  createDataset,
  deleteDataset,
  fetchDatasetList,
  fetchDatasetUsage,
  updateDataset
} from '@/service/api/dataset';

const loading = ref(false);
const dataSource = ref<Api.Valuation.DatasetDef[]>([]);
const modalVisible = ref(false);
const viewModalVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();

const formData = ref<Partial<Api.Valuation.DatasetDef>>({
  id: '',
  name: '',
  description: '',
  status: '1',
  enabled: true
});

const viewData = ref<Api.Valuation.DatasetDef>({} as Api.Valuation.DatasetDef);

const modalTitle = computed(() => (isEdit.value ? '编辑映射集' : '新增映射集'));

const columns = [
  {
    title: '映射集ID',
    dataIndex: 'id',
    key: 'id',
    width: 150
  },
  {
    title: '映射集名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '映射集描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '生效状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '是否启用',
    dataIndex: 'enabled',
    key: 'enabled',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'operate',
    width: 180,
    fixed: 'right' as const
  }
];

const formRules: Record<string, any> = {
  id: [{ required: true, message: '请输入映射集ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入映射集名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择生效状态', trigger: 'change' }]
};

// 获取数据列表
async function fetchData() {
  loading.value = true;
  try {
    const { data: resData } = await fetchDatasetList();
    if (resData) {
      dataSource.value = resData;
    }
  } finally {
    loading.value = false;
  }
}

// 新增
function handleAdd() {
  isEdit.value = false;
  formData.value = {
    id: '',
    name: '',
    description: '',
    status: '1',
    enabled: true
  };
  modalVisible.value = true;
}

// 编辑
function handleEdit(record: Api.Valuation.DatasetDef) {
  isEdit.value = true;
  formData.value = { ...record };
  modalVisible.value = true;
}

// 查看
function handleView(record: Api.Valuation.DatasetDef) {
  viewData.value = record;
  viewModalVisible.value = true;
}

// 删除
async function handleDelete(record: Api.Valuation.DatasetDef) {
  // 先检查使用情况
  const { data: usageData } = await fetchDatasetUsage(String(record.id));
  if (usageData && !usageData.canDelete) {
    window.$message?.warning(`映射集 ${record.name} 正在被使用，无法删除`);
    return;
  }

  window.$modal?.confirm({
    title: '确认删除',
    content: `确定要删除映射集 "${record.name}" 吗？`,
    onOk: async () => {
      const { data: resData } = await deleteDataset(String(record.id));
      if (resData) {
        window.$message?.success('删除成功');
        fetchData();
      }
    }
  });
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value?.validate();

    if (isEdit.value) {
      const { data: resData } = await updateDataset(String(formData.value.id!), formData.value);
      if (resData) {
        window.$message?.success('更新成功');
        modalVisible.value = false;
        fetchData();
      }
    } else {
      console.info('formData.value', formData.value);
      const { data: resData } = await createDataset(formData.value as any);
      if (resData) {
        window.$message?.success('创建成功');
        modalVisible.value = false;
        fetchData();
      }
    }
  } catch {
    // 表单验证失败
  }
}

// 取消
function handleCancel() {
  modalVisible.value = false;
  formRef.value?.resetFields();
}

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div>
    <ACard :bordered="false" class="card-wrapper">
      <div class="mb-4 flex items-center justify-between">
        <h3 class="text-lg font-semibold">映射集管理</h3>
        <AButton type="primary" @click="handleAdd">
          <template #icon>
            <icon-carbon:add />
          </template>
          新增映射集
        </AButton>
      </div>

      <ATable :columns="columns" :data-source="dataSource" :loading="loading" :pagination="false" row-key="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <ATag :color="record.status === '1' ? 'green' : 'red'">
              {{ record.status === '1' ? '生效' : '失效' }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'enabled'">
            <ATag :color="record.enabled ? 'blue' : 'default'">
              {{ record.enabled ? '启用' : '禁用' }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'operate'">
            <ASpace>
              <AButton type="link" size="small" @click="handleEdit(record as Api.Valuation.DatasetDef)">编辑</AButton>
              <AButton type="link" size="small" @click="handleView(record as Api.Valuation.DatasetDef)">查看</AButton>
              <AButton type="link" size="small" danger @click="handleDelete(record as Api.Valuation.DatasetDef)">
                删除
              </AButton>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新增/编辑弹窗 -->
    <AModal v-model:open="modalVisible" :title="modalTitle" :width="600" @ok="handleSubmit" @cancel="handleCancel">
      <AForm ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <AFormItem label="映射集ID" name="id">
          <AInput v-model:value="formData.id" :disabled="isEdit" placeholder="请输入映射集ID" />
        </AFormItem>
        <AFormItem label="映射集名称" name="name">
          <AInput v-model:value="formData.name" placeholder="请输入映射集名称" />
        </AFormItem>
        <AFormItem label="映射集描述" name="description">
          <ATextarea v-model:value="formData.description" placeholder="请输入映射集描述" :rows="3" />
        </AFormItem>
        <AFormItem label="生效状态" name="status">
          <ASelect v-model:value="formData.status" placeholder="请选择生效状态">
            <ASelectOption value="ACTIVE">生效</ASelectOption>
            <ASelectOption value="INACTIVE">失效</ASelectOption>
          </ASelect>
        </AFormItem>
        <AFormItem label="是否启用" name="enabled">
          <ASwitch v-model:checked="formData.enabled" />
        </AFormItem>
      </AForm>
    </AModal>

    <!-- 查看详情弹窗 -->
    <AModal v-model:open="viewModalVisible" title="映射集详情" :width="600" :footer="null">
      <ADescriptions :column="1" bordered>
        <ADescriptionsItem label="映射集ID">
          {{ viewData.id }}
        </ADescriptionsItem>
        <ADescriptionsItem label="映射集名称">
          {{ viewData.name }}
        </ADescriptionsItem>
        <ADescriptionsItem label="映射集描述">
          {{ viewData.description || '-' }}
        </ADescriptionsItem>
        <ADescriptionsItem label="生效状态">
          <ATag :color="viewData.status === '1' ? 'green' : 'red'">
            {{ viewData.status === '1' ? '生效' : '失效' }}
          </ATag>
        </ADescriptionsItem>
        <ADescriptionsItem label="是否启用">
          <ATag :color="viewData.enabled ? 'blue' : 'default'">
            {{ viewData.enabled ? '启用' : '禁用' }}
          </ATag>
        </ADescriptionsItem>
        <ADescriptionsItem label="创建时间">
          {{ viewData.createTime }}
        </ADescriptionsItem>
        <ADescriptionsItem label="修改时间">
          {{ viewData.updateTime }}
        </ADescriptionsItem>
        <ADescriptionsItem label="创建人">
          {{ viewData.createBy || '-' }}
        </ADescriptionsItem>
        <ADescriptionsItem label="修改人">
          {{ viewData.updateBy || '-' }}
        </ADescriptionsItem>
      </ADescriptions>
    </AModal>
  </div>
</template>

<style scoped>
.card-wrapper {
  min-height: calc(100vh - 200px);
}
</style>
